from random import randint, choice
import copy
import time
import pickle
import os

from jplur.player import Player
import jplur.tables as tables
import jplur

def menu_who(self, input=0):
	self.Send({"action": "menu_clear"})
	total = 0
	lines = []
	for entry in jplur.server.players:
		dude = entry.player
		if dude.logged == 1:
			total += 1
			lines.append( '#:'+dude.color+" "+dude.name+"#:ffffff     Level:"+str(dude.level) )
	self.Send( {"action":"menu", "data":['',' '+str(total)+' players in game:',''] } )
	self.Send( {"action":"menu", "data":lines } )
	self.Send( {"action":"line_entry", "data":0} ) #ensure that the line entry is not on
	self.menu = [0,0]
	
def menu_help(self, input=0):
	self.Send({"action": "menu_clear"})
	
	
	self.Send( {"action":"menu", "data":['',
										' #:7bd8ff--------- Game Commands ---------',
										' ',
										' move   : NUMPAD           up/down : <,>      ','',
										' quit   : q                who     : @        ','',
										' dig    : d                run     : r        ','',
										' look   : l(not working)                      ','',
										' chat   : TAB to enter a line, RETURN to send.',
										' help   : ?                                   ',
										'','',
										' Hints: Harder enemies are found deep below,  ',
										'        you will have to dig to find them.    '
										] } )
	
	self.Send( {"action":"line_entry", "data":0} ) #ensure that the line entry is not on
	self.menu = [0,0]

def jump_look(self, dir):
	myLoc = self.player.location
	things = jplur.map.things_in_view(myLoc)
	candidates = []
	x,y = 0,0
	for entity in things:
		eLoc = entity.location
		if eLoc[1] - myLoc[1] >= 0:
			x = 1
		if eLoc[1] - myLoc[1] >= 0:
			x = -1
		if eLoc[2] - myLoc[2] >= 0:
			y = 1
		if eLoc[2] - myLoc[2] >= 0:
			y = -1
		
		if eLoc[1] == x and eLoc[2] == y:
			candidates.append(entity)
	closest = [100000, 0]
	for entry in candidates:
		dist = jplur.map.entity_hash.get_distance(myLoc, entry.location)
		if dist < closest[0]:
			closest = [dist, entry]
	
	if len(candidates) > 0:
		return closest[1]
	
def menu_look(self, input=0):
	if self.menu[0] != 2:
		self.menu = [2,0]
		jplur.tmp_selected = self.player
	selected = jplur.tmp_selected
	
	self.Send({"action": "menu_clear"})
	self.Send( {"action":"menu", "data":['',' Looking.                     [ESC]'] } )
	self.Send( {"action":"line_entry", "data":0} )
	self.Send( {"action":"highlite", "data":selected.id})
	
	if input in tables.directions():
		found = jump_look( self, tables.directions()[input] )
		if found:
			self.Send( {"action":"highlite", "data":found.id})
	
	if input == 27:
		self.menu = [0,0]
		self.Send( {"action":"highlite", "data":-1})
		self.Send({"action": "menu_clear"})

def menu_die(self, input=0):
	if self.menu[0] != 3:
		self.menu = [3,0]
	if self.menu[1] == 0:
		self.Send({"action": "menu_clear"})
		self.Send( {"action":"menu", "data":['',' You have died. Permamently.',' Press any key to quit.'] } )
		self.Send( {"action":"line_entry", "data":0} )
		self.menu[1] = 1
		self.player.delete()
	else:
		print "die called"
		if input != 0:
			self.Send({"action": "quit"})
			print "removing savefile:",self.name+'.sav'
			os.remove('./players/'+self.name+'.sav')
			try:
				self.Close()
			except:
				print "error removing player"

def menu_run(self, input=0):
	
	if self.menu[0] != 4:
		self.menu = [4,0]
	if self.menu[1] == 0:
		self.Send({"action": "menu_clear"})
		self.Send( {"action":"menu", "data":['',' Run in what direction?             [ESC to cancel]'] } )
		self.Send( {"action":"line_entry", "data":0} )
		self.menu[1] = 1	
		print "ready to run!:",self.menu
	
	elif self.menu[1] == 1:
		if input in tables.directions():
			self.player.run(input)
			self.Send({"action": "menu_clear"})
			self.Send( {"action":"menu", "data":['',' Running                [ESC to stop]'] } )
				
	if input == 27:
		self.player.running = 0
		self.Send({"action": "menu_clear"})
		self.Send( {"action":"line_entry", "data":0} )
		self.menu = [0,0]
		
		
def menu_dig(self, input=0):
	#get dig direction
	#find out if diggable else exit
	#set player to digging state
	#player clears menu if done, and alerts players to tile change
	#menu can cancel and clear digging state
	if self.menu[0] != 5:
		self.menu = [5,0]
	if self.menu[1] == 0:
		self.Send({"action": "menu_clear"})
		self.Send( {"action":"menu", "data":['',' Dig in what direction?             [ESC to cancel]', '',' < and > keys to build up or down stair.'] } )
		self.Send( {"action":"line_entry", "data":0} )
		self.menu[1] = 1	

	
	elif self.menu[1] == 1:
		if input in tables.directions():
			self.player.dig(input)
			self.Send({"action": "menu_clear"})
			self.Send( {"action":"menu", "data":['',''] } )
			self.Send( {"action":"line_entry", "data":0} )
			self.menu = [0,0]	
	if input == 27:
		self.player.digging = 0
		self.Send({"action": "menu_clear"})
		self.Send( {"action":"line_entry", "data":0} )
		self.menu = [0,0]
		
def menu_login(self, input=0):
	print "menu, ", self.menu
	if self.menu[0] != 1:
		self.menu = [1,0]
	lines = [     "",
				  "#:dd8b32                 Welcome to GridFolk",
                  "#:ffffff                        -----       ",
                          "                   an experimental  ",
                          "                     multiplayer    ",
                          "                      roguelike     ",
                  "",
				  "",
				  "",
                  "#:00a2ff a) Log in with existing character",
				  "",
				  "#:00a2ff b) Create new character"
	]
	
	if self.menu[1] == 0:
		self.Send({"action": "menu_clear"})
		self.Send( {"action":"menu", "data":lines } )
		self.Send( {"action":"line_entry", "data":0} ) #ensure that the line entry is not on
		self.menu[1] = 1
	elif self.menu[1] == 1:
		if input == 97:
			self.Send({"action": "menu_clear"})
			self.Send( {"action":"menu", "data":[""," Enter your character's name:"] } )
			self.Send( {"action":"line_entry", "data":1} ) 
			self.menu[1] = 3
		elif input == 98:
			self.Send({"action": "menu_clear"})
			self.Send( {"action":"menu", "data":[""," Enter a name for your new character:"] } )
			self.Send( {"action":"line_entry", "data":1} ) 
			self.menu[1] = 2
			
	elif self.menu[1] == 2: #new character name
		print input
		if len(input) <= 2 or len(input) >= 12:
			self.Send({"action": "menu_clear"})
			self.Send({"action": "menu", "data":[""," Must be 3 to 12 characters, try again:"]})	
			self.Send( {"action":"line_entry", "data":1} ) 
		elif input.lower() in ['look', 'get', 'kill', 'kil','loo', 'who', 'help'] or ":" in input or "/" in input or "#" in input:
			self.Send({"action": "menu_clear"})
			self.Send({"action": "menu", "data":[""," Illegal name, try again:"]})
			self.Send( {"action":"line_entry", "data":1} ) 
		else:
			
			try:

				savefile = open('./players/'+input+'.sav', 'r') #load player object
				
				savefile.close()
				self.menu = [1,0]
				self.Send({"action": "message", "data":["[SERVER]:sorry that name is taken."]})
				menu_login(self)
				return
			except:	
				self.name = input
				self.Send({"action": "menu_clear"})
				self.Send({"action": "menu", "data":[""," Welcome "+str(self.name)+"!", " Enter your password:"]})
				self.Send( {"action":"line_entry", "data":1} ) 
				self.menu[1] = 4
			
			
	elif self.menu[1] == 4: #new character password
		if type(input) != str:
			return
		if len(input) <= 2 or len(input) >= 12:
			self.Send({"action": "menu_clear"})
			self.Send({"action": "menu", "data":[""," Must be 3 to 12 characters, try again:"]})	
			self.Send( {"action":"line_entry", "data":1} ) 
		else:
			################ Here we actually create the player object
			self.player = Player(self) #wonky, self is the channel
			self.player.password = input
			self.player.name = self.name

			self.Send({"action": "menu_clear"})
			self.Send({"action": "menu", "data":[""," Password set.", ""," Enter your class:","",
													"#:009904 a)green     #:ffffff   Faster than most ",'',
													"#:0d78e5 b)blue      #:ffffff   Tougher  ",'',
													"#:e5640d c)orange    #:ffffff   Learns quickly  ",'',
													"#:ded3bc d)off-white #:ffffff   Average  ",'',
													"#:8648dc e)purple    #:ffffff   Assassin  ",'',
													]})
			self.Send( {"action":"line_entry", "data":0} ) 
			self.menu[1] = 5		
	
	elif self.menu[1] == 5:
		go = 0
		if input == 97:
			self.player.color = "009904"
			self.player.char_class = "green"
			go = 1
		if input == 98:
			self.player.color = "0d78e5"
			self.player.char_class = "blue"
			go = 1
		if input == 99:
			self.player.color = "e5640d"
			self.player.char_class = "orange"
			go = 1
		if input == 100:
			self.player.color = "ded3bc"
			self.player.char_class = "off-white"
			go = 1
		if input == 101:
			self.player.color = "8648dc"
			self.player.char_class = "purple"
			go = 1
			
		if go == 1:
			self.Send({"action": "menu_clear"})
			self.Send( {"action":"menu", "data":[""," Entering game.."] } )
			self.player.logged = 1
			self.logged = 1
			self.Send( {"action":"line_entry", "data":0} ) 
			self.menu = [0,0]	
			self.player.start()
			#try:
			self.player.save()
			self.Send( {"action":"menu", "data":[""," Character saved.."] } )
			menu_help(self)
			#except:
			#	self.Send( {"action":"menu", "data":[""," Error saving character!"] } )
			
	elif self.menu[1] == 3: #existing character
		
		if len(input) <= 2 or len(input) >= 12:
			self.Send({"action": "menu_clear"})
			self.Send({"action": "menu", "data":[""," Must be 3 to 12 characters, try again:"]})	
			self.Send( {"action":"line_entry", "data":1} ) 
		elif input.lower() in ['look', 'get', 'kill', 'kil','loo', 'who', 'help'] or ":" in input or "/" in input or "#" in input:
			self.Send({"action": "menu_clear"})
			self.Send({"action": "menu", "data":[""," Illegal name, try again:"]})
			self.Send( {"action":"line_entry", "data":1} ) 
		else:
			
			try:

				savefile = open('./players/'+input+'.sav', 'r') #load player object
				self.player = pickle.load(savefile) #go ahead and load it, we'll remove it if pass is incorrect
				self.player.channel = self #this wasn't pickled
				savefile.close()
				self.menu[1] = 6

				self.Send({"action": "menu_clear"})
				self.Send({"action": "menu", "data":[""," Welcome back "+str(self.player.name)+".", " Enter your password:"]})
				self.Send( {"action":"line_entry", "data":1} ) 

			except:	
				
				self.Send({"action": "menu_clear"})
				self.Send({"action": "menu", "data":[""," Sorry there is no player of that name.", " Try again:"]})
				self.Send( {"action":"line_entry", "data":1} ) 
						
	elif self.menu[1] == 6: #existing character password
		if len(input) <= 2 or len(input) >= 12:
			self.Send({"action": "menu_clear"})
			self.Send({"action": "menu", "data":[""," Must be 3 to 12 characters, try again:"]})	
			self.Send( {"action":"line_entry", "data":1} ) 
		elif input != self.player.password:
			print input, self.player.password

			self.menu = [1,0]
			self.Send({"action": "message", "data":["[SERVER]:Incorrect password."]})
			menu_login(self)
		else:

			self.Send({"action": "menu_clear"})
			menu_help(self)
			self.player.logged = 1
			self.logged = 1
			self.Send( {"action":"line_entry", "data":0} ) 
			self.menu = [0,0]	
			self.player.start()
			self.player.oldkey = 0
			self.player.move( [0,0,0] ) #force look around